package com.antler.smt.portal.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.OrderConstant;
import com.antler.smt.constant.RoleConstant;
import com.antler.smt.entity.*;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.mapper.*;
import com.antler.smt.response.admin.GetUserListResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.service.portal.MatchUserService;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.LogUtil;
import com.antler.smt.utils.SmsUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 匹配项目专员
 *
 * @author zhangyi
 * @date 2018/4/10 9:09
 */
@Service
public class MatchUserServiceImpl implements MatchUserService {

    /**
     * 日志
     */
    private static Logger log = LogUtil.get();

    @Autowired
    private UserInfoMapper matchUserMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderEntityMapper orderEntityMapper;

    @Autowired
    private RequirementEntityMapper requirementEntityMapper;

    @Autowired
    private SupplierEntityMapper supplierEntityMapper;

    @Autowired
    private UserEntityMapper userEntityMapper;

    @Autowired
    private UserRoleInfoMapper userRoleInfoMapper;


    /**
     * 获取一个匹配的项目专员实体
     *
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<GetUserListResp> getMatchUser(long requirementId,long memberId) {
        Result result = null;

        GetUserListResp userInfo = getUser();

        //返回随机匹配的项目专员实体
        result = new Result(userInfo);

        OrderEntity orderInfoByRequirement = orderInfoMapper.getOrderInfoByRequirement(requirementId);
        SupplierEntity supplierEntity = null;
        if(orderInfoByRequirement != null) {
            supplierEntity  = supplierEntityMapper.selectByPrimaryKey(orderInfoByRequirement.getRequirementId());
        }

        if(supplierEntity != null) {
            //发送短信至项目专员
            SendSmsResponse sendSmsResponse = SmsUtil.sendPickUpSms(userInfo.getMobile(),
                    userInfo.getRealName(),
                    new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(DateUtil.stampToDate(System.currentTimeMillis())),
                    "已经匹配到" + supplierEntity.getCompanyName() + "服务商");
            if (sendSmsResponse.getCode().equalsIgnoreCase("OK") && sendSmsResponse.getMessage().equalsIgnoreCase("OK")) {
                result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
            } else {
                result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
            }
        }

        //生成初级订单 创建订单实体 订单初步形成
        OrderEntity orderEntity = new OrderEntity();

        //生成订单号 时间戳+会员id
        orderEntity.setOrderNo(String.valueOf(System.currentTimeMillis()+""+memberId));

        //添加项目专员id
        orderEntity.setConnectUserId(userInfo.getId());

        //添加需求id
        orderEntity.setRequirementId(requirementId);

        //0待对接服务商 1待付款 2待确认付款 3待生产完成  4待收货 6待评价 7待付款给服务商 8结束 100驳回
        orderEntity.setStatus(OrderConstant.ORDER_WAIT_JOIN_SUPPLIER);

        //添加交货时间
        RequirementEntity requirementEntity = requirementEntityMapper.selectByPrimaryKey(requirementId);

        /*
            交货时间修改了 2018-04-28 17:27
         */
//        orderEntity.setEndTime(requirementEntity.getEndline());

        //添加收货地址id
        orderEntity.setReceiveAddressId(requirementEntity.getAddressId());

        //初始化订单时间
        orderEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //初始化更新时间
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //创建一个订单
        int i = orderEntityMapper.insertSelective(orderEntity);

        boolean flag = (0 == i);
        if (flag) {
            return new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        } else {
            return result;
        }
    }



    /**
     * 匹配商务专员
     *
     * @param requirementId
     * @param memberId
     * @return
     */
    @Override
    public Result<UserEntity> matchBusinessAffairs(long requirementId, long memberId) {
        Result result = null;

        //随机返回的商务专员信息
        UserEntity user = getBusinessAffairsUser();

        //发送短信给商务专员
        SendSmsResponse sendSmsResponse = SmsUtil.sendPickUpSms(user.getMobile(),
                user.getRealName()+":商务专员",
                new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date(System.currentTimeMillis())),
                "请您抓紧时间对接项目专员");
        Result result1 = (sendSmsResponse.getCode().equalsIgnoreCase("OK") && sendSmsResponse.getMessage().equalsIgnoreCase("OK")?
                            new Result(ResultCodeEnum.OPERATION_SUCCESS):new Result(ResultCodeEnum.APPEND_DATA_ERROR));

        //生成初级订单
        OrderEntity orderEntity = new OrderEntity();

        //生成订单号 时间戳+会员id
        orderEntity.setOrderNo(String.valueOf(System.currentTimeMillis()+""+memberId));

        //添加商务专员id
        orderEntity.setBusinessAffairsUserId(user.getId());

        //添加需求id
        orderEntity.setRequirementId(requirementId);

        //添加创建日期
        orderEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
        //添加交货时间
        RequirementEntity requirementEntity = requirementEntityMapper.selectByPrimaryKey(requirementId);

/*        //小时为单位
        Integer endline = requirementEntity.getEndline();
        //转换成毫秒
        Long time = Long.parseLong(String.valueOf(endline*60*60*1000));

        //添加交货时间
        orderEntity.setEndTime(DateUtil.stampToDate(time+));
*/
        //添加收货地址id
        orderEntity.setReceiveAddressId(requirementEntity.getAddressId());

        //初始化更新时间
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //采购商待支付
        orderEntity.setStatus(OrderConstant.ORDER_WAIT_PAYMENT);

        //创建一个订单
        int i = orderEntityMapper.insertSelective(orderEntity);

        result = (0 == i)?new Result(ResultCodeEnum.APPEND_DATA_ERROR):new Result(user);

        return result;
    }


    /**
     * 随机返回项目专员信息
     *
     * @return
     */
    @Override
    public Result<GetUserListResp> getUserInfo() {
        List<Long> userIdList = matchUserMapper.getUserIdList();
        int random = (int)Math.floor(Math.random()*userIdList.size());
        return new Result (matchUserMapper.getUserInfo(userIdList.get(random)));
    }

    /**
     * 获取项目专员信息
     *
     * @return
     */
    public GetUserListResp getUser(){
        //下单的数量
        long number = 0;
        //最终匹配的项目专员id
        long userId = 0;
        //获取id集合
        List<Long> userIdList = matchUserMapper.getUserIdList();

        //存储项目专员的id值和处理单量
        Map<Long, Long> userMap = new LinkedHashMap<>();

        for (int i = 0; i < userIdList.size(); i++) {
            number = orderInfoMapper.getUserDisposeOrderList(userIdList.get(i));
            userMap.put(userIdList.get(i), number);
        }
        Set<Long> longs = userMap.keySet();
        Iterator<Long> iterator = longs.iterator();
        while (iterator.hasNext()) {
            Long key = iterator.next();
            Long value = userMap.get(key);

            //获取订单数最少的项目专员id
            if (number >= value) {
                number = value;
                userId = key;
            }
        }

        //项目专员的个数
        int  userSize = userIdList.size();
        //各个项目专员的订单量相同
        if (userId == 0) {
            //随机分配
            userId = (long) Math.random() * userSize + 1;
        }
        //获取单数少的项目专员
        GetUserListResp userInfo = matchUserMapper.getUserInfo(userId);
        return  userInfo;
    }

    /**
     * 根据规则获取商务专员信息
     *
     * @return
     */
    public UserEntity getBusinessAffairsUser(){
        //商务专员id列表
        List<Long> userIdList = userRoleInfoMapper.getUserId(RoleConstant.BUSINESS_USER);
        //默认商务专员id
        Long defaultId = RoleConstant.DEFAULT_USER_ID;
        if(0 != userIdList.size()) {
            log.info("获取到多个商务专员id... ...");
            defaultId = userIdList.get((int) Math.floor(Math.random() * userIdList.size()));
        }

        return  userEntityMapper.selectByPrimaryKey(defaultId);
    }

    @Override
    public Result<GetUserListResp> getMatchUserInfo(long orderId) {
        return null;
    }
}
